<template>
  <div>
    <SearchContainer @search="getData" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item name="pyjm" label="" class="">
          <a-input v-model:value="formState.pyjm" class="w-64" placeholder="药品名称/助记码/药品编号/单号" />
        </a-form-item>
        <a-form-item name="dateRange" label="制单日期">
          <a-range-picker v-model:value="formState.dateRange" class="w-64" format="YYYY-MM-DD " value-format="YYYY-MM-DD" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="flex">
        <a-button class="mb-2" type="primary" @click="onAdd"> 新增 </a-button>
      </div>
      <BaseTable :data-source="tableData" fill :loading="loading" :scroll="{ x: 1800 }" column-code="000305" :pagination="pagination">
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'status'">
            <!-- 0：待确认 1：已确认 2：已作废 -->
            <a-tag v-if="record.status === '2'" color="red">已作废</a-tag>
            <a-tag v-else-if="record.status === '1'" color="green">已确认</a-tag>
            <a-tag v-else color="blue">待确认</a-tag>
          </template>
          <template v-if="column.dataIndex === 'consumeDh'">
            <PopoverTable :config="detailConfig" :params="{ ckbh: record.storeCode, consumeDh: record.consumeDh }" :width="1200">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'drugName'">
                  <MedicineInfo :value="{ mc: popRecord.drugName, gg: popRecord.gg, cj: popRecord.cj }" />
                </template>
              </template>
              {{ record.consumeDh }}
            </PopoverTable>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" size="small" :disabled="record.status !== '0'" @click="onDetail(record)">明细</a-button>
              <BaseButton confirm-text="是否确认消耗?" type="link" size="small" :disabled="record.status !== '0'" @click="confirmConsume(record)">
                确认消耗
              </BaseButton>
              <BaseButton
                confirm-text="是否作废此消耗单?"
                type="text"
                danger
                size="small"
                :disabled="record.status !== '0'"
                @click="saveConsumeStatus(record, '2')"
              >
                作废
              </BaseButton>
              <TableMoreButton>
                <a-button type="link" size="small" :disabled="record.status !== '0'" @click="onEditOpen(record)">修改</a-button>
                <a-button type="link" size="small" :disabled="record.status === '2'" @click="onPrint(record)"> 打印 </a-button>
              </TableMoreButton>
            </a-space>
          </template>
        </template>
      </BaseTable>
    </a-card>
    <Edit v-model:open="editOpen" :title="editTitle" :row-data="rowData" @success="onSuceess" />
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import useUserStore from '@/store/user'
import Edit from './Edit'

const { empId } = useUserStore()

const editOpen = ref(false)
const editTitle = ref('')
const rowData = ref({})
const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const formState = ref({
  ckbh: '',
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  pyjm: ''
})

const detailConfig = ref({
  url: '/drugStorage/consume/getKcConsumeDetailList',
  columnCode: '000312',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      xh: index + 1
    }))
  }
})
const onAdd = () => {
  rowData.value = {}
  editOpen.value = true
  editTitle.value = '新增消耗单'
}
const onSuceess = (e) => {
  getData()
  router.push({
    path: '/drug-consume/drug-consume/detail',
    query: {
      dh: e.consumeDh
    }
  })
}
const { loading, tableData, getData, pagination } = useTable({
  url: '/drugStorage/consume/getKcConsumeEntitieList',
  immediate: false,
  formatParams: () => {
    return {
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1],
      pyjm: formState.value.pyjm,
      ckbh: formState.value.ckbh,
      materialType: route.query?.routerType || undefined // 防疫物资
    }
  }
})
const getDepartInfo = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
  if (res.code !== 0) message.error(res.msg || '获取登录人科室失败')
  formState.value.ckbh = res.data?.ksdm
  getData()
}

const onEditOpen = (record) => {
  rowData.value = { ...record }
  editOpen.value = true
  editTitle.value = '修改消耗单'
}
const saveConsumeStatus = async (record, type) => {
  const formData = {
    id: record.id,
    status: type
  }
  const res = await post('/drugStorage/consume/doSaveKcConsume', formData)
  if (res.code !== 0) return message.error(res.msg || type === '1' ? '确认失败' : '作废失败')
  message.success(res.msg)
  getData()
}
const confirmConsume = async (record) => {
  const res = await post('drugStorage/consume/doKcConsumeInventoryConsumption', { consumeDh: record.consumeDh })
  if (res.code !== 0) return message.error(res.msg || '确认消耗失败')
  message.success(res.msg)
  getData()
}
const onDetail = (record) => {
  router.push({
    path: '/drug-consume/drug-consume/detail',
    query: {
      dh: record.consumeDh
    }
  })
}

const onPrint = async (row) => {
  // /drugStorage/psiform/printWarehousingList
  const { code, msg, data } = await post('/drugStorage/psiform/printKcConsumeEntitie', { consumeDh: row.consumeDh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
onMounted(() => {
  getDepartInfo()
})
</script>
